package org.zzh.exception;

import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

@ControllerAdvice
public class GlobalExceptionHandler {

    // 处理404异常
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ModelAndView handle404Exception(NoHandlerFoundException e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("code", 404);
        modelAndView.addObject("message", "页面未找到");
        // 添加异常信息
        modelAndView.addObject("exception", e);
        // 指定404页面的路径
        modelAndView.setViewName("/WEB-INF/pages/error/404");
        return modelAndView;
    }

    // 处理500异常
    // 处理500异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView handle500Exception(Exception e) {
        ModelAndView modelAndView = new ModelAndView();

        // 添加错误代码和消息
        modelAndView.addObject("code", 500);
        modelAndView.addObject("message", "服务器内部错误");

        // 添加异常信息
        modelAndView.addObject("exception", e.getMessage());

        // 提取堆栈信息
        StringBuilder stackTrace = new StringBuilder();
        for (StackTraceElement element : e.getStackTrace()) {
            stackTrace.append(element.toString()).append("<br>");
        }
        modelAndView.addObject("stackTrace", stackTrace.toString());

        // 指定500页面的路径
        modelAndView.setViewName("/WEB-INF/pages/error/500");
        return modelAndView;
    }

    // 处理权限不足异常 (AuthorizationException)
    @ExceptionHandler(AuthorizationException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ModelAndView handleAuthorizationException(AuthorizationException e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("code", 403);
        modelAndView.addObject("message", "您没有权限访问该资源");
        modelAndView.addObject("exception", e.getMessage());
        modelAndView.setViewName("/WEB-INF/pages/error/403");
        return modelAndView;
    }

}